<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import MEcharts from '/@/components/MEcharts/MEcharts.vue';
  const props = defineProps({
    dataSet: { type: Object as () => any, required: true },
    dataReal: { type: Object as () => any, required: true },
    datax: { type: Object as () => any, required: true },
    title: { type: String, required: true },
    max: { type: Number, default: 250000 },
    min: { type: Number, default: 0 },
  });

  const chartRef = ref();

  const option = {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'axis',
      appendToBody: true, // 关键设置
      axisPointer: {
        type: 'shadow',
      },
    },
    bar: {
      barGap: '30%',
      barCategoryGap: '30%',
    },
    legend: {
      data: ['目标', '实际'],
      top: 15,
      right: 5,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisTick: {
        alignWithLabel: true,
      },
    },
    yAxis: {
      min: props.min,
      max: props.max,
      type: 'value',
      // interval: 10,
      axisLabel: {
        formatter: '{value}',
      },
      splitLine: {
        show: true,
      },
    },
    series: [
      {
        name: '目标',
        type: 'bar',
        barGap: 0,
        itemStyle: {
          color: '#5470c6', // 使用蓝色表示目标
        },
        data: props.dataSet,
      },
      {
        name: '实际',
        type: 'bar',
        itemStyle: {
          color: '#fac858', // 使用橙色表示实际
        },
        data: props.dataReal,
      },
    ],
  };

  const myChart = ref<InstanceType<typeof MEcharts>>();
  const updateChart = () => {
    option.series[0].data = props.dataSet ?? [];
    option.series[1].data = props.dataReal ?? [];
    option.xAxis.data = props.datax ?? [];
    myChart.value?.resizeHandler();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      updateChart();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
  });

  watch(
    () => [props.datax, props.dataSet, props.dataReal],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <m-echarts :option="option"></m-echarts>
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
